package com.youdianstar.app.common.base

import android.app.Activity
import android.os.Bundle
import android.os.PersistableBundle

import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider

import com.youdianstar.app.common.callback.NetworkStateManager
import com.youdianstar.app.common.ex.getVmClazz
import com.youdianstar.app.common.util.AppManager
import com.youdianstar.app.common.util.ToastUtil
import com.youdianstar.app.common.util.dialog.DialogUtil

import com.vmadalin.easypermissions.EasyPermissions
import com.youdianstar.app.common.auko.AnkoInternals


/**
 * File: BaseBVActivity
 * Author: 82149 Create: 2021/10/30 11:51
 * Changes (from 2021/10/30)
 * --------------------------------------------------
 * description: 可以替换布局的 activity,变化因素直接在实现子类中处理
 * ---------------------------------------------------
 *
 */
abstract class BaseBVActivity<VM : BaseViewModel> : AppCompatActivity() , EasyPermissions.PermissionCallbacks {
    //lateinit var mBinding: Any //放到 页面里单独初始化
    lateinit var mViewModel: VM

    private var viewModelId: Int? = null

    abstract fun initVariableId(): Int?

    /**创建ViewModel: 方法0:配合koin使用,需要网络接口时 ;方法1:创建ViewModel*/
    abstract fun initViewModel(): VM

    fun <DB : ViewDataBinding> initViewBinding(layoutId: Int): DB {
        val binding: DB = DataBindingUtil.setContentView(this, layoutId)
        binding.lifecycleOwner = this
        return binding
    }

    fun createViewModel(): VM {
        return ViewModelProvider(this).get(getVmClazz(this))
    }

    override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
        super.onCreate(savedInstanceState, persistentState)
        viewModelId = initVariableId()
        mViewModel = initViewModel()

        viewModelId?.let {
            setDataBinding(mViewModel,it)
        }
        mViewModel.let { lifecycle.addObserver(it) }

        AppManager.instance.addActivity(this)
        init(savedInstanceState)
    }

    abstract fun setDataBinding(vm :VM, vId:Int)

    abstract fun destroyBinding()

    override fun onDestroy() {
        super.onDestroy()
        mViewModel.let {
            lifecycle.removeObserver(it)
        }
        destroyBinding()
        AppManager.instance.removeActivity(this)
    }

    private fun init(savedInstanceState: Bundle?) {
        registerUIChangeLiveDataCallBack()
        initViewLayout()
        initData()
        initLiveObserver()
        NetworkStateManager.instance.mNetworkStateCallback.observe(this, Observer {
            onNetworkStateChanged(it)
        })
    }

    abstract fun initViewLayout()

    abstract fun initData()

    abstract fun initLiveObserver()


    /**
     * 网络变化监听 子类重写
     */
    open fun onNetworkStateChanged(isNetConnect: Boolean) {}

    private fun registerUIChangeLiveDataCallBack(){
        mViewModel.finishEvent.observe(this, Observer {
            finish()
        })
        mViewModel.backPressedEvent.observe(this, Observer {
            onBackPressed()
        })
        mViewModel.startActivityEvent.observe(this, Observer { t ->

            val activity: Class<out Activity> = t[BaseViewModel.CLASS] as Class<out Activity>
            val params: Array<out Pair<String, Any?>> = t[BaseViewModel.BUNDLE] as Array<out Pair<String, Any?>>
            startActivity(AnkoInternals.createIntent(this, activity, params))
        })

        mViewModel.loadingNetEvent.observe(this, Observer {
            showLoadingDialog(it)
        })
        mViewModel.dismissNetEvent.observe(this, Observer {
            dismissDialog()
        })
    }

    /**
     * dialog 展示
     */
    fun showLoadingDialog(title: String) {
        DialogUtil.instance.showLoading(this)
    }

    /**
     * 取消
     */
    fun dismissDialog() {
        DialogUtil.instance.dismissLoading()
    }

    /**
     * toast
     *
     * @param text
     */
    fun toastShow(text: String?, type: Int = 0) {
        val prefix = if (type == 1) "AT-" else ""
        ToastUtil.show(this,"$prefix$text")
    }

    /*********************************授权*******************************/

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {
        //权限允许
    }

    override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {
        //权限不允许
    }

    val REQUEST_PERMISSION_CODE = 100

    /**
     * 请求权限-EasyPermissions
     * @param permissions 权限内容 多个
     */
    fun requestPermission(tips :String, vararg permissions: String, granted :() -> Unit = {}){
        if (EasyPermissions.hasPermissions(this, *permissions)){
            granted.invoke()
        } else {
            EasyPermissions.requestPermissions(host = this,rationale = tips,requestCode = REQUEST_PERMISSION_CODE,perms = permissions)
        }
    }

}